package com.zhiyou100.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.ConvertException;
import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entity.Student;

import java.util.List;

/**
 * @author yang
 * @className StudentService
 * @packageName com.zhiyou100.service
 * @Description TODO student 服务层
 * @date 2020-08-12 22:09
 */
public class StudentService implements AutoCloseable {

    StudentDao studentDao = new StudentDao();

    public List<Student> getAll() {
        return studentDao.getAll();
    }

    public Student getOneBySid(String sid) {
        try {
            final int i = Integer.parseInt(sid);
            return studentDao.getOneBySid(i);
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }
    }

    public void addOne(String sname, String sage, String sex, String sdanYuan, String score) {
        try {
            int toSage = Convert.convert(int.class, sage);
            final Boolean toSdangYuan = Convert.convert(Boolean.class, sdanYuan);
            final Float toScore = Convert.convert(Float.class, score);

            // 转换没有问题,创建对象
            final Student student = new Student(sname, sex, toScore, toSdangYuan, toSage);
            studentDao.addOne(student);
        } catch (ConvertException e) {
            // 转换出错，抛出异常
            throw new RuntimeException(e);
        }

    }

    public void addOne(Student student) {
        studentDao.addOne(student);

    }

    public void delOneBySid(String sid) {
        final Integer toSid = Convert.convert(int.class, sid);
        studentDao.delOneBySid(toSid);
    }

    public void updateOne(String sid, String sname, String sage, String sex, String sdanYuan, String score) {
        try {
            final Integer toSid = Convert.convert(int.class, sid);
            int toSage = Convert.convert(int.class, sage);
            final Boolean toSdangYuan = Convert.convert(Boolean.class, sdanYuan);
            final Float toScore = Convert.convert(Float.class, score);

            // 转换没有问题,创建对象,更新一个
            final Student student = new Student(toSid, sname, sex, toScore, toSdangYuan, toSage);
            studentDao.updateOne(student);
        } catch (ConvertException e) {
            // 转换出错，抛出异常
            throw new RuntimeException(e);
        }
    }

    public void updateOne(Student student) {
        studentDao.updateOne(student);
    }


    @Override
    public void close() throws Exception {
        if (studentDao != null) {
            studentDao.close();
        }
    }
}
